import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { FileInfo } from '@/types/file'
import * as trashApi from '@/api/modules/trash'
import type { 
  TrashStats, 
  TrashFilesQuery, 
  PageResponse,
  RestoreFilesRequest,
  PermanentDeleteRequest 
} from '@/api/modules/trash'

/**
 * 回收站状态管理
 */
export const useTrashStore = defineStore('trash', () => {
  // ==================== 状态定义 ====================
  
  // 回收站文件列表
  const trashFiles = ref<FileInfo[]>([])
  
  // 分页信息
  const pagination = ref({
    page: 0,
    size: 20,
    totalElements: 0,
    totalPages: 0,
    first: true,
    last: true,
    empty: true
  })
  
  // 排序信息
  const sortConfig = ref({
    sortBy: 'deletedAt',
    sortDir: 'desc' as 'asc' | 'desc'
  })
  
  // 统计信息
  const stats = ref<TrashStats>({
    totalFiles: 0,
    totalSize: 0,
    expiringSoon: 0
  })
  
  // 加载状态
  const loading = ref(false)
  const statsLoading = ref(false)
  
  // 选中的文件
  const selectedFiles = ref<FileInfo[]>([])
  
  // 操作状态
  const restoring = ref(false)
  const deleting = ref(false)
  const emptying = ref(false)
  
  // ==================== 计算属性 ====================
  
  // 是否有选中文件
  const hasSelectedFiles = computed(() => selectedFiles.value.length > 0)
  
  // 选中文件数量
  const selectedCount = computed(() => selectedFiles.value.length)
  
  // 选中文件总大小
  const selectedSize = computed(() => {
    return selectedFiles.value
      .filter(file => !file.isDirectory)
      .reduce((total, file) => total + (file.fileSize || 0), 0)
  })
  
  // 是否全选
  const isAllSelected = computed(() => {
    return trashFiles.value.length > 0 && selectedFiles.value.length === trashFiles.value.length
  })
  
  // 是否部分选中
  const isIndeterminate = computed(() => {
    return selectedFiles.value.length > 0 && selectedFiles.value.length < trashFiles.value.length
  })
  
  // ==================== 操作方法 ====================
  
  /**
   * 加载回收站文件列表
   */
  const loadTrashFiles = async (query: TrashFilesQuery = {}) => {
    try {
      loading.value = true
      
      const params = {
        page: query.page ?? pagination.value.page,
        size: query.size ?? pagination.value.size,
        sortBy: query.sortBy ?? sortConfig.value.sortBy,
        sortDir: query.sortDir ?? sortConfig.value.sortDir
      }
      
      const response = await trashApi.getTrashFiles(params)
      const data = response.data
      
      trashFiles.value = data.content
      pagination.value = {
        page: data.number,
        size: data.size,
        totalElements: data.totalElements,
        totalPages: data.totalPages,
        first: data.first,
        last: data.last,
        empty: data.empty
      }
      
      // 更新排序配置
      if (query.sortBy) sortConfig.value.sortBy = query.sortBy
      if (query.sortDir) sortConfig.value.sortDir = query.sortDir
      
      // 清空选中状态
      selectedFiles.value = []
      
    } catch (error) {
      console.error('加载回收站文件失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }
  
  /**
   * 加载统计信息
   */
  const loadStats = async () => {
    try {
      statsLoading.value = true
      const response = await trashApi.getTrashStats()
      stats.value = response.data
    } catch (error) {
      console.error('加载回收站统计信息失败:', error)
      throw error
    } finally {
      statsLoading.value = false
    }
  }
  
  /**
   * 还原文件
   */
  const restoreFiles = async (request: RestoreFilesRequest) => {
    try {
      restoring.value = true
      await trashApi.restoreFiles(request)
      
      // 重新加载数据
      await Promise.all([
        loadTrashFiles(),
        loadStats()
      ])
      
    } catch (error) {
      console.error('还原文件失败:', error)
      throw error
    } finally {
      restoring.value = false
    }
  }
  
  /**
   * 彻底删除文件
   */
  const permanentDeleteFiles = async (request: PermanentDeleteRequest) => {
    try {
      deleting.value = true
      await trashApi.permanentDeleteFiles(request)
      
      // 重新加载数据
      await Promise.all([
        loadTrashFiles(),
        loadStats()
      ])
      
    } catch (error) {
      console.error('彻底删除文件失败:', error)
      throw error
    } finally {
      deleting.value = false
    }
  }
  
  /**
   * 清空回收站
   */
  const emptyTrash = async () => {
    try {
      emptying.value = true
      await trashApi.emptyTrash()
      
      // 重新加载数据
      await Promise.all([
        loadTrashFiles(),
        loadStats()
      ])
      
    } catch (error) {
      console.error('清空回收站失败:', error)
      throw error
    } finally {
      emptying.value = false
    }
  }
  
  /**
   * 切换文件选中状态
   */
  const toggleFileSelection = (file: FileInfo) => {
    const index = selectedFiles.value.findIndex(f => f.id === file.id)
    if (index > -1) {
      selectedFiles.value.splice(index, 1)
    } else {
      selectedFiles.value.push(file)
    }
  }
  
  /**
   * 全选/取消全选
   */
  const toggleSelectAll = () => {
    if (isAllSelected.value) {
      selectedFiles.value = []
    } else {
      selectedFiles.value = [...trashFiles.value]
    }
  }
  
  /**
   * 清空选中状态
   */
  const clearSelection = () => {
    selectedFiles.value = []
  }
  
  /**
   * 检查文件是否被选中
   */
  const isFileSelected = (file: FileInfo) => {
    return selectedFiles.value.some(f => f.id === file.id)
  }
  
  /**
   * 刷新数据
   */
  const refresh = async () => {
    await Promise.all([
      loadTrashFiles(),
      loadStats()
    ])
  }
  
  /**
   * 重置状态
   */
  const reset = () => {
    trashFiles.value = []
    selectedFiles.value = []
    pagination.value = {
      page: 0,
      size: 20,
      totalElements: 0,
      totalPages: 0,
      first: true,
      last: true,
      empty: true
    }
    sortConfig.value = {
      sortBy: 'deletedAt',
      sortDir: 'desc'
    }
    stats.value = {
      totalFiles: 0,
      totalSize: 0,
      expiringSoon: 0
    }
  }
  
  // ==================== 返回状态和方法 ====================
  
  return {
    // 状态
    trashFiles,
    pagination,
    sortConfig,
    stats,
    loading,
    statsLoading,
    selectedFiles,
    restoring,
    deleting,
    emptying,
    
    // 计算属性
    hasSelectedFiles,
    selectedCount,
    selectedSize,
    isAllSelected,
    isIndeterminate,
    
    // 方法
    loadTrashFiles,
    loadStats,
    restoreFiles,
    permanentDeleteFiles,
    emptyTrash,
    toggleFileSelection,
    toggleSelectAll,
    clearSelection,
    isFileSelected,
    refresh,
    reset
  }
})
